package membervalidator

import (
	"fmt"
	"time"
	"yunj/pkg/global"
	"yunj/pkg/yunj/app/consts"
	"yunj/pkg/yunj/app/data"
	"yunj/pkg/yunj/app/enum/stateenum"
	"yunj/pkg/yunj/app/model"
	"yunj/pkg/yunj/app/service/admin/adminservice"
	"yunj/pkg/yunj/util"

	"github.com/gin-gonic/gin"
	"github.com/worklz/go-validate"
)

type Member struct {
	validate.Validator
	GinContext *gin.Context
	IsInfo     bool // 是否是查看个人信息
}

func (v *Member) HandleDatas(datas map[string]interface{}, scene string) (err error) {
	if scene == "FormSubmit" {
		err = v.HandleDatasByFormSubmit(datas)
		if err != nil {
			return
		}
	}
	return
}

func (v *Member) HandleDatasByFormSubmit(datas map[string]interface{}) (err error) {
	datas = util.MapFloat64ToUints(datas)
	currTime := time.Now().In(time.Local)
	dbMember := &model.AdminMember{
		Name:      util.MapKeyValue(datas, "name", ""),
		UpdatedAt: &currTime,
	}
	// id
	currOperatorId := adminservice.GetLoginMemberId(v.GinContext)
	var id uint64
	if v.IsInfo {
		id = currOperatorId
	} else if idRaw, exists := datas["id"]; exists {
		var idVal uint64
		if idVal, err = util.ToUint64(idRaw); err == nil && idVal > 0 {
			if currOperatorId != 1 && idVal == 1 {
				err = fmt.Errorf("系统内置初始超管账户不允许修改！")
				return
			}
			id = idVal
		}
	}
	// username
	username := util.MapKeyValue(datas, "username", "")
	// 判断是否存在
	usernameExistsQuery := global.MySQL.Model(&model.AdminMember{}).Where("`username` = ?", username)
	if id > 0 {
		usernameExistsQuery.Where("`id` != ?", id)
	}
	var usernameExistsCount int64
	if err = usernameExistsQuery.Count(&usernameExistsCount).Error; err != nil {
		return fmt.Errorf("数据查询异常！%v", err)
	}
	if usernameExistsCount > 0 {
		return fmt.Errorf("账户【%s】已存在！", username)
	}
	dbMember.Username = username
	// password
	password := util.MapKeyValue(datas, "password", "")
	if id <= 0 && password == "" {
		// 新增密码为空，输入默认密码
		password = consts.ADMIN_MEMBER_DEFAULT_PASSWORD
	}
	if password != "" {
		dbMember.PasswordSalt = util.RandomStr(16)
		dbMember.PasswordHash = util.PasswordGenerate(password, dbMember.PasswordSalt)
	}
	if id > 0 {
		// 编辑
		dbMember.Id = id
	} else {
		// 新增
		dbMember.CreatedAt = &currTime
		dbMember.State = stateenum.NORMAL
	}
	datas["dbMember"] = dbMember
	// 部门/岗位
	if data.Department.HasNormalData() {
		// department_ids
		departmentIdsVal := util.MapKeyValue(datas, "department_ids", []any{})
		departmentIds := util.ToUint64Slice(departmentIdsVal)
		if len(departmentIds) > 0 {
			dbMemberDepartments := []*model.AdminMemberDepartment{}
			for _, departmentId := range departmentIds {
				dbMemberDepartments = append(dbMemberDepartments, &model.AdminMemberDepartment{
					MemberId:     dbMember.Id,
					DepartmentId: departmentId,
				})
			}
			datas["dbMemberDepartments"] = dbMemberDepartments
			// department_postion_ids
			departmentPostionIdsVal := util.MapKeyValue(datas, "department_postion_ids", []any{})
			departmentPostionIds := util.ToUint64Slice(departmentPostionIdsVal)
			dbMemberDepartmentPostions := []*model.AdminMemberDepartmentPostion{}
			for _, departmentPostionId := range departmentPostionIds {
				dbMemberDepartmentPostions = append(dbMemberDepartmentPostions, &model.AdminMemberDepartmentPostion{
					MemberId:            dbMember.Id,
					DepartmentPostionId: departmentPostionId,
				})
			}
			datas["dbMemberDepartmentPostions"] = dbMemberDepartmentPostions
		}
	}
	// role_ids
	roleIdsVal := util.MapKeyValue(datas, "role_ids", []any{})
	roleIds := util.ToUint64Slice(roleIdsVal)
	dbMemberRoles := []*model.AdminMemberRole{}
	for _, roleId := range roleIds {
		dbMemberRoles = append(dbMemberRoles, &model.AdminMemberRole{
			MemberId: dbMember.Id,
			RoleId:   roleId,
		})
	}
	datas["dbMemberRoles"] = dbMemberRoles
	return
}
